package com.qfedu.edu.seckill.orderservice.slot.impl;

import com.alibaba.druid.util.StringUtils;
import com.qfedu.edu.seckill.exception.BusinessException;
import com.qfedu.edu.seckill.manager.RedisManager;
import com.qfedu.edu.seckill.orderservice.slot.generic.GenericSlot;
import com.qfedu.edu.seckill.result.R;
import com.qfedu.edu.seckill.result.ResponseCode;
import com.qfedu.edu.seckill.utils.HttpResponseUtils;
import lombok.extern.slf4j.Slf4j;
import org.qfedu.edu.seckill.service.IJwtService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author xiaobobo
 * @title: SellStatusSlot
 * @projectName cd-java-2404-seckill-parent
 * @description: TODO
 * @date 2025/2/6  9:47
 */
@Component
@Slf4j
public class SellStatusSlot extends GenericSlot {

    @Autowired
    private RedisManager redisManager;

    @Autowired
    private IJwtService jwtService;

    @Override
    public int getOrder() {
        return Integer.MIN_VALUE + 2;
    }

    @Override
    public void dealRequest(HttpServletRequest request, HttpServletResponse response) {
        log.info("SellStatusCheckInterceptor执行了....");
        //你想用户的购买状态有那些呢?  正在买  买失败了   买成功了
        //这个用户购买状态  我们可以使用Redis来存在
        // 使用这个Redis中的String数据类型  key：sell:status:用户id:课程id   //buying   success   fail
        //首先组装这个用户购买状态的key
        String userId = getUserId(request);
        //拿到这个课程的id
        String classId = request.getParameter("classId");
        //然后组装这个key
        String userSellStatusKey = "sell:status:" + userId + ":" + classId;
        //然后去Redis中查询这个用户的购买状态
        String status = redisManager.getString(userSellStatusKey);
        //有四种情况
        if (StringUtils.isEmpty(status)) {
            //说明第一次购买
            log.info("用户第一次购买...");
            return ;
        }
        //还有第二种和三种情况
        if (StringUtils.equals(status, "buying") || StringUtils.equals(status, "success")) {
            log.info("用户正在购买或者已经秒杀过商品了不能重复秒杀");
            throw new BusinessException(ResponseCode.BUY_REPEAT_EXCEPTION);
        }
        //如果执行到这里说明购买失败
        log.info("用户购买过这个商品但是失败可以从新秒杀");
    }

    /**
     * 通过request拿到这个用户id
     *
     * @param request
     * @return
     */
    private String getUserId(HttpServletRequest request) {
        String token = request.getHeader("token");
        //然后解析这个token
        return jwtService.getUserId(token);
    }
}
